package com.test.realcityalfa.json.responses;

import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.test.realcityalfa.beans.AdCountResponseBean;
import com.test.realcityalfa.beans.ResponseBean;

public class AdCountResponseBuilder implements ResponseBuilder{
	public static final String RESPONSE_NEW_COUNT = "new";
	public static final String RESPONSE_TRANSACTION_TYPE_COUNTS = "transaction_types";
	public static final String RESPONSE_SALE_COUNT = "sale";
	public static final String RESPONSE_RENT_COUNT = "rent";
	public static final String RESPONSE_AUCTION_COUNT = "auction";
	
	private JSONObject _jsonResponse;
	
	public AdCountResponseBuilder()
	{
		
	}
	
	@Override
	public ResponseBean getStructuredResponse(String jsonResponseString) throws JsonResponseException 
	{
		//TODO implement logic for converion between json string and bean
		if(jsonResponseString == null || jsonResponseString == ""){return null;}
		try
		{
			createJsonObject(jsonResponseString);
			return convertStringToBean();
		}		
		catch(JSONException ex)
		{
			performException(ex);			
		}
		return null;		
	}
	
	private void createJsonObject(String jsonResponseString) throws JSONException
	{
		this._jsonResponse = new JSONObject(jsonResponseString);
	}

	private ResponseBean convertStringToBean() throws JSONException
	{
		AdCountResponseBean countsBean = new AdCountResponseBean();//new ResponseBean();
		
		this._jsonResponse = this._jsonResponse.getJSONObject(RESPONSE_RESULT_ROOT);
		countsBean.setTotalCount(this._jsonResponse.getString(RESPONSE_TOTAL_COUNT));
		countsBean.setNewCount(this._jsonResponse.getString(RESPONSE_NEW_COUNT));
		
		this._jsonResponse = this._jsonResponse.getJSONObject(RESPONSE_TRANSACTION_TYPE_COUNTS);
		countsBean.setSaleCount(this._jsonResponse.getString(RESPONSE_SALE_COUNT));
		countsBean.setRentCount(this._jsonResponse.getString(RESPONSE_RENT_COUNT));
		countsBean.setAuctionCount(this._jsonResponse.getString(RESPONSE_AUCTION_COUNT));		
		
		return countsBean;
	}
	
	private void performException(Exception ex) throws JsonResponseException
	{
		Log.d(getClass().getName(), ex.getMessage());
		throw new JsonResponseException(ex.getLocalizedMessage(), ex);
	}	
}
